package com.jy.horny.function

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import com.google.gson.Gson
import com.jy.chat.kit.RongIM
import com.jy.chat.kit.conversationlist.ConversationListFragment
import com.jy.chat.kit.manager.UnReadMessageManager
import com.jy.chat.kit.userinfo.RongUserInfoManager
import com.jy.chat.kit.userinfo.UserDataProvider
import com.jy.chat.kit.utils.RongConfigUtil
import com.jy.horny.base.BaseVMActivity
import com.jy.horny.base.HttpRequestListener
import com.jy.horny.databinding.ActivityMainBinding
import com.jy.horny.function.home.HomeFragment
import com.jy.horny.function.me.MeFragment
import com.jy.horny.model.IMTokenModel
import com.jy.horny.model.PolicyModel
import com.jy.horny.model.ServerUserInfo
import com.jy.horny.model.UserInfoBaseModel
import com.jy.horny.weight.NavigationLayout
import com.lib.module_base.utils.SaveDeviceUtil
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.UserInfo
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

class MainActivity : BaseVMActivity<ActivityMainBinding, MainViewModel>(
    ActivityMainBinding::inflate,
    MainViewModel::class.java
) {
    val scope = MainScope()

    override fun initData() {
        initialViews()
    }

    private fun initialViews() {
        binding.viewPager.offscreenPageLimit = 3
        binding.viewPager.isScrollable = false
        binding.viewPager.adapter = object :
            FragmentPagerAdapter(supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            override fun getCount(): Int = 3
            override fun getItem(position: Int): Fragment {
                return when (position) {
                    0 -> HomeFragment()
                    1 -> ConversationListFragment()
                    else -> MeFragment()
                }
            }
        }
        binding.navigation.attach(binding.viewPager)
        binding.navigation.setListener(object : NavigationLayout.Callback {
            override fun onItemClick(position: Int): Boolean {
                binding.viewPager.setCurrentItem(position, false)
                return false
            }

            override fun onItemClickAgain(position: Int) {
            }
        })
        //请求token，连接融云
        mViewModel?.getIMToken(object : HttpRequestListener<IMTokenModel>() {
            override fun addRequestParams(params: HashMap<String, Any>) {

            }

            override fun success(t: IMTokenModel?) {
                t?.let { RongConfigUtil.connectIM(it.token, this@MainActivity) }
            }
        })
        //获取协议
        mViewModel?.getPolicy(object :HttpRequestListener<PolicyModel>(){
            override fun addRequestParams(params: HashMap<String, Any>) {
                params["code"]=2
            }

            override fun success(t: PolicyModel?) {
                SaveDeviceUtil.savePolicyUrl(Gson().toJson(t))
            }

        })
        //获取客服信息
        mViewModel?.getServer(object :HttpRequestListener<List<ServerUserInfo>>(){
            override fun addRequestParams(params: HashMap<String, Any>) {
                params["code"]=1
            }

            override fun success(t: List<ServerUserInfo>?) {
                if (!t.isNullOrEmpty()){
                    t.apply {
                        RongIM.getInstance().refreshUserInfoCache(
                            UserInfo(
                                t[0].userCode,
                                t[0].name,
                                Uri.parse(t[0].iocn)
                            )
                        )
                        SaveDeviceUtil.saveServiceUserCode(t[0].userCode)
                    }
                }
            }
        })

        setIMInfo()
    }

    /**
     * 进行IM的相关配置
     */
    private fun setIMInfo() {
        //设置用户头像/昵称
        RongUserInfoManager.getInstance()
            .setUserInfoProvider(object : UserDataProvider.UserInfoProvider {
                override fun getUserInfo(userId: String?): UserInfo? {
                    userId?.let {
                        scope.launch {
                            mViewModel?.getUserInfoBase(object :
                                HttpRequestListener<UserInfoBaseModel>() {
                                override fun addRequestParams(params: HashMap<String, Any>) {
                                    params["userCode"] = userId
                                }

                                override fun success(t: UserInfoBaseModel?) {
                                    t?.apply {
                                        val userInfo = UserInfo(
                                            t.userCode,
                                            t.nickName,
                                            Uri.parse(t.avatarUrl)
                                        )
                                         RongUserInfoManager.getInstance()
                                            .refreshUserInfoCache(userInfo)
                                    }

                                }

                            })

                        }
                    }
                    return null
                }
            }, true)
        //设置未读消息
        UnReadMessageManager.getInstance()
            .addObserver(arrayOf(Conversation.ConversationType.PRIVATE)
            ) { count -> binding.navigation.setUnreadNum(count) }
    }

    companion object {
        fun start(context: Context?) {
            SaveDeviceUtil.saveToken("eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJzdWIiOiIxNzkwNjU1OTg0NzIyNjA4MTI4IiwianRpIjoiMTc5MDY1NTk4NDcyMjYwODEyOCIsImlzcyI6InNlY3VyaXR5IiwiaWF0IjoxNzE3Mzg3MDI3LCJhdWQiOiJzZWN1cml0eS1hbGwiLCJleHAiOjE3MTc5OTE4Mjd9.14sLCN9Hr_ZZ2bp-LpT3Z6WNalAc1GbZQX7TGND9xT0")
            context?.startActivity(Intent(context, MainActivity::class.java))
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        scope.cancel()
    }

}